package com.construction.api.config.interceptor;

import com.construction.api.config.holder.PayloadHolder;
import com.construction.api.domain.model.header.Header;
import com.construction.api.domain.model.token.Payload;
import com.construction.api.service.TokenService;
import com.construction.api.util.JwtTokenUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author dybin
 * @Date: 2021/7/1 22:24
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class JwtInterceptor implements HandlerInterceptor {

    private final TokenService tokenService;
    private final JwtTokenUtil jwtTokenUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (tokenService.isSkip(handler)) {
            return true;
        }
        Header header = Header.of(request, jwtTokenUtil);
        if (tokenService.verifyToken(header)) {
            Payload payload = (Payload) tokenService.resolvToken(header);
            PayloadHolder.add(payload);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        PayloadHolder.remove();
    }
}

